/*
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 11:55:46
 * @LastEditors: cxguo
 * @LastEditTime: 2019-08-20 16:32:13
 */
import { listData as listCateData } from '@/api/goods/cate'
import { listAll as listUnitAll } from '@/api/goods/unit'
import Vue from 'vue'

const state = {}

const mutations = {
  SET_DATA: (state, { name, data }) => {
    Vue.set(state, name, data)
  },
  SET_CATE_DATA: (state, data) => {
    state.cateData = data
  }
}

const actions = {
  /**
   * 获取商品分类
   * @param {*} param0
   * @param {*} refresh
   */
  getCateData({ commit, state }, refresh = false) {
    const dataName = 'cateData'
    if (state[dataName] && !refresh) {
      return state.cateData
    }
    listCateData().then(res => {
      if (res.data.flag) {
        const data = JSON.parse(res.data.data)
        const cateData = data[0].children
        commit('SET_DATA', { name: dataName, data: cateData })
      }
    })
  },
  /**
   * 获取商品 - 单位名称
   */
  getGoodUnitData({ commit, state }, refresh = false) {
    const dataName = 'unitData'
    if (state[dataName] && !refresh) {
      return state.cateData
    }
    listUnitAll().then(res => {
      if (res.data.flag) {
        commit('SET_DATA', { name: dataName, data: res.data.data })
      }
    }).catch(err => {
      console.log(err)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

